package com.didi.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.didi.gulimall.common.constant.ProductConstant;
import com.didi.gulimall.common.utils.PageUtils;
import com.didi.gulimall.common.utils.Query;
import com.didi.gulimall.product.dao.AttrDao;
import com.didi.gulimall.product.dao.AttrGroupDao;
import com.didi.gulimall.product.dao.CategoryDao;
import com.didi.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.didi.gulimall.product.entity.AttrEntity;
import com.didi.gulimall.product.entity.AttrGroupEntity;
import com.didi.gulimall.product.entity.CategoryEntity;
import com.didi.gulimall.product.service.AttrAttrgroupRelationService;
import com.didi.gulimall.product.service.AttrService;
import com.didi.gulimall.product.service.CategoryService;
import com.didi.gulimall.product.vo.AttrGroupWithAttrsVo;
import com.didi.gulimall.product.vo.AttrResponseVO;
import com.didi.gulimall.product.vo.AttrVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author 10626
 */
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttr(AttrVO attrVO) {
        this.save(attrVO);
        // 保存分组信息
        AttrAttrgroupRelationEntity attrGroupRelation = new AttrAttrgroupRelationEntity();
        attrGroupRelation.setAttrId(attrVO.getAttrId());
        attrGroupRelation.setAttrGroupId(attrVO.getAttrGroupId());
///        attrGroupRelation.setAttrSort();
        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() == attrVO.getAttrType() && attrVO.getAttrGroupId() != null) {
            attrAttrgroupRelationService.saveAttr(attrGroupRelation);
        }
    }

    @Override
    public PageUtils getAttrGroupList(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVO> respVos = records.stream().map(attrEntity -> {
            AttrResponseVO attrRespVo = new AttrResponseVO();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            if ("base".equalsIgnoreCase(attrType)) {
                QueryWrapper<AttrAttrgroupRelationEntity> attrWrapper = new QueryWrapper<>();
                attrWrapper.eq("attr_id", attrEntity.getAttrId());
                AttrAttrgroupRelationEntity attrgroupRelation = attrAttrgroupRelationService.getOne(attrWrapper);
                if (attrgroupRelation != null && attrgroupRelation.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            if (attrEntity.getCatelogId() != null) {
                CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Override
    public AttrResponseVO getAttrInfo(Long attrId) {
        AttrResponseVO attrResponseVO = new AttrResponseVO();
        AttrEntity attrEntity = this.baseMapper.selectById(attrId);
        BeanUtils.copyProperties(attrEntity, attrResponseVO);
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_id", attrEntity.getAttrId());
        AttrAttrgroupRelationEntity attrgroupRelation = attrAttrgroupRelationService.getOne(wrapper);
        if (attrgroupRelation != null && attrgroupRelation.getAttrGroupId() != null) {
            AttrGroupEntity attrGroup = attrGroupDao.selectById(attrgroupRelation.getAttrGroupId());
            attrResponseVO.setGroupName(attrGroup.getAttrGroupName());
            attrResponseVO.setAttrGroupId(attrgroupRelation.getAttrGroupId());
        }
        if (attrEntity.getCatelogId() != null) {
            CategoryEntity category = categoryDao.selectById(attrEntity.getCatelogId());
            attrResponseVO.setCatelogName(category.getName());
            List<Long> cateLogPath = categoryService.findCateLogPath(attrEntity.getCatelogId());
            attrResponseVO.setCatelogPath(cateLogPath);
        }
        return attrResponseVO;
    }

    @Override
    public void updateAttr(AttrVO attrVO) {
        this.updateById(attrVO);
        // 修改分组
        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() == attrVO.getAttrType()) {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            relation.setAttrId(attrVO.getAttrId());
            relation.setAttrGroupId(attrVO.getAttrGroupId());
            QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("attr_id", relation.getAttrId());
            int count = attrAttrgroupRelationService.count(wrapper);
            if (count > 1) {
                throw new RuntimeException("属性分组异常");
            }
            if (count == 1) {
                if (relation.getAttrGroupId() == null) {
                    attrAttrgroupRelationService.remove(wrapper);
                }
                attrAttrgroupRelationService.update(relation, wrapper);
            }
            if (count == 0) {
                attrAttrgroupRelationService.save(relation);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_group_id", attrgroupId);
        wrapper.select("attr_id");
        List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationService.list(wrapper);
        if (list != null && list.isEmpty()) {
            return null;
        }
        List<Long> attrIds = list.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        return (List<AttrEntity>) this.listByIds(attrIds);
    }

    @Override
    public PageUtils attrNoRelation(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1)、当前分类下的其他分组
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id", catelogId);
        List<AttrGroupEntity> group = attrGroupDao.selectList(wrapper);
        List<Long> groupIds = group.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        //2.2)、这些分组关联的属性
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("attr_group_id", groupIds);
        List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationService.list(queryWrapper);
        List<Long> attrIds = list.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        //2.3)、从当前分类的所有属性中移除这些属性；
        QueryWrapper<AttrEntity> attrWrapper = new QueryWrapper<>();
        attrWrapper.eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (!attrIds.isEmpty()) {
            attrWrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            attrWrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrWrapper);
        return new PageUtils(page);
    }

    @Override
    public void deleteAttrRelation(List<AttrAttrgroupRelationEntity> attrGroupWithAttrsVos) {
        if (attrGroupWithAttrsVos != null && attrGroupWithAttrsVos.size() > 0) {
            attrAttrgroupRelationService.deleteBatchRelation(attrGroupWithAttrsVos);
        }
    }

    @Override
    public void saveAttrRelation(List<AttrAttrgroupRelationEntity> attrGroupWithAttrs) {
        attrAttrgroupRelationService.saveBatch(attrGroupWithAttrs);
    }

    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id", catelogId);
        //1、查出当前分类下的所有属性分组，
        List<AttrGroupEntity> attrGroups = attrGroupDao.selectList(wrapper);
        //2、查出每个属性分组的所有属性
        return attrGroups.stream().map(attrGroupEntity -> {
            AttrGroupWithAttrsVo attrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(attrGroupEntity, attrsVo);
            List<AttrEntity> attrs = attrService.getRelationAttr(attrsVo.getAttrGroupId());
            attrsVo.setAttrs(attrs);
            return attrsVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        if (attrIds!=null&&attrIds.size()>0){
            return this.baseMapper.selectSearchAttrIds(attrIds);
        }else {
            return null;
        }
    }
}
